package com.glasses.orm.spring;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

/**
 * 业务异常抛出
 * Created by 汪超 on 2016/5/6.
 */
public class BusinessException extends RuntimeException {
    private static final long serialVersionUID = 3152616724785436891L;

    private static ThreadLocal<JSONObject> threadLocal = new ThreadLocal<>();

    public BusinessException(String frdMessage) {
        super(createFriendlyErrMsg(frdMessage));
    }

    public BusinessException(Throwable throwable) {
        super(throwable);
    }

    public BusinessException(Throwable throwable, String frdMessage) {
        super(throwable);
    }

    public BusinessException(String frdMessage, String targetClsName) {
        super(createFriendlyErrMsg(frdMessage, targetClsName));
    }

    /**
     * 异常友好抛出
     *
     * @param msgBody 提示主体
     * @return
     */
    private static String createFriendlyErrMsg(String msgBody) {
        String prefixStr = "抱歉, ";
        String suffixStr = "  请稍后再试或与管理员联系！";

        StringBuffer friendlyErrMsg = new StringBuffer("");

        friendlyErrMsg.append(prefixStr);

        friendlyErrMsg.append(msgBody);

        friendlyErrMsg.append(suffixStr);

        return friendlyErrMsg.toString();
    }

    /**
     * 异常友好抛出
     *
     * @param msgBody 提示主体
     * @return
     */
    private static String createFriendlyErrMsg(String msgBody, String targetClsName) {
        JSONObject jsonObject = initializeLocalJSONObject();
        if(isJSONValid(msgBody)){
            if(targetClsName.equals("Service")) {
                jsonObject.put(targetClsName, "[Dao] " + JSON.parseObject(msgBody).getString("Dao"));
            }else if(targetClsName.equals("Controller")){
                jsonObject.put(targetClsName, "[Service] " + JSON.parseObject(msgBody).getString("Service"));
            }
        }else {
            jsonObject.put(targetClsName, createFriendlyErrMsg(msgBody));
        }
        return jsonObject.toString();
    }

    private static JSONObject initializeLocalJSONObject(){
        if(threadLocal.get() == null){
            threadLocal.set(new JSONObject());
        }
        return threadLocal.get();
    }

    /**
     * 暴力解析:Alibaba fastjson
     * @param test
     * @return
     */
    public final static boolean isJSONValid(String test) {
        try {
            JSONObject.parseObject(test);
        } catch (JSONException ex) {
            try {
                JSONObject.parseArray(test);
            } catch (JSONException ex1) {
                return false;
            }
        }
        return true;
    }
}
